"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 防篡改
Case Name   : 锁定不在有效时间内的帐号
Create At   : 2022/3/7
Owner       : opentestcase012
Description :
    1.设置参数并重启数据库enableSeparationOfDuty=on
    gs_guc set -N all -I all -c enableSeparationOfDuty=on;
    gs_om -t restart
    2.创建已过期用户和未生效用户
    drop user if exists [已过期/未生效用户] cascade;
    CREATE user [已过期用户] WITH PASSWORD 'test@123'
    VALID BEGIN '2016-12-28 00:00:00' VALID UNTIL '2016-12-28 23:59:59';
    CREATE user [未生效用户] WITH PASSWORD 'test@123'
    VALID BEGIN '2026-12-28 00:00:00' VALID UNTIL '2026-12-28 23:59:59';
    3.使用已过期/未生效用户登录
    gsql -d postgres -p [端口号] -r -U [已过期/未生效用户] -W [用户密码] -c "select user;"
    4.查看用户账户的状态
    select * from pg_user_status;
    5.清理环境
    drop user if exists [自定义用户] cascade;
    gs_guc set -N all -I all -c enableSeparationOfDuty=off;
    gs_om -t restart
Expect      :
    1.成功
    2.成功
    3.登录失败
    4.查询成功
    5.清理环境成功
History     :
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class Security(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_node = Node(node='PrimaryDbUser')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.u_name = 'u_security_authen_account_0001'
        self.user_valid = {f'{self.u_name}_01': '2016-12-29',
                           f'{self.u_name}_02': '2026-12-29'}
        self.default_value1 = self.common.show_param('enableSeparationOfDuty')

    def test_security(self):
        text = '-----step1：设置参数并重启数据库enableSeparationOfDuty=on; ' \
               'expect:成功-----'
        self.log.info(text)
        mod_msg = self.pri_sh.execute_gsguc('set',
                                            self.constant.GSGUC_SUCCESS_MSG,
                                            'enableSeparationOfDuty=on')
        self.assertTrue(mod_msg, '执行失败:' + text)
        result = self.pri_sh.restart_db_cluster()
        self.assertTrue(result, '执行失败' + text)

        for user, valid in self.user_valid.items():
            text = '-----step2：创建已过期用户和未生效用户 expect:成功-----'
            self.log.info(text)
            create_cmd = f"drop user if exists {user} cascade; " \
                f"create user {user} with " \
                f"password '{macro.GAUSSDB_INIT_USER_PASSWD}'" \
                f" valid begin '{valid} 00:00:00'" \
                f" valid until '{valid} 23:59:59'; "
            msg = self.pri_sh.execut_db_sql(create_cmd)
            self.log.info(msg)
            self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, msg,
                          '执行失败:' + text)
            self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG, msg,
                          '执行失败:' + text)

            text = f'-----step3：使用已过期/未生效用户登录; expect:登录失败-----'
            self.log.info(text)
            sql = 'select user;'
            connect = f'-U {user} -W {macro.GAUSSDB_INIT_USER_PASSWD}'
            msg = self.pri_sh.execut_db_sql(sql, sql_type=connect)
            self.log.info(msg)
            self.assertIn(
                'The account is not within the period of validity',
                msg, '执行失败:' + text)

            text = f'-----查看当前日期 expect:成功-----'
            self.log.info(text)
            msg = self.pri_sh.execut_db_sql('select current_date;')
            self.log.info(msg)
            self.assertIn('1 row', msg, '执行失败:' + text)
            current_date = msg.splitlines()[-2]

            text = f'-----step4：查看用户账户的状态; expect:查询成功-----'
            self.log.info(text)
            sql = f"select a.usename,a.valbegin,a.valuntil,b.locktime," \
                f"b.failcount,b.rolstatus,b.passwordexpired " \
                f"from pg_user a full join pg_user_status b " \
                f"on a.usesysid=b.roloid and a.usename='{user}';"
            msg = self.pri_sh.execut_db_sql(sql)
            self.log.info(msg)
            self.assertIn(f'{valid} 00:00:00', msg, '执行失败:' + text)
            self.assertIn(f'{valid} 23:59:59', msg, '执行失败:' + text)
            self.assertIn(current_date, msg, '执行失败:' + text)
            self.assertIn('0 |         0 |               0', msg,
                          '执行失败:' + text)

    def tearDown(self):
        self.log.info('-----step5：清理环境-----')
        text1 = '-----删除用户 expect:成功-----'
        self.log.info(text1)
        drop_msg = []
        for user in self.user_valid.keys():
            drop_cmd = f"drop user if exists {user} cascade; "
            msg = self.pri_sh.execut_db_sql(drop_cmd)
            self.log.info(msg)
            drop_msg.append(msg)

        text2 = '-----修改参数enableSeparationOfDuty为初始值并重启数据库 expect:成功-----'
        self.log.info(text2)
        mod_msg1 = self.pri_sh.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'enableSeparationOfDuty='
                                             f'{self.default_value1}')
        restart_res = self.pri_sh.restart_db_cluster()

        self.log.info('-----断言tearDown执行成功-----')
        self.assertEqual(2,
                         drop_msg.count(self.constant.DROP_ROLE_SUCCESS_MSG),
                         '执行失败:' + text1)
        self.assertTrue(mod_msg1, '执行失败:' + text2)
        self.assertTrue(restart_res, '执行失败:' + text2)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
